/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.fanli.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.CashbackManager;
import com.mol.market.common.util.CashbackManager.CashbackTask;
import com.mol.market.common.util.TopBar;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.DownloadItem;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.AppListAdapter.ViewBinder;
import com.mol.market.common.widget.LazyloadListActivity;
import com.mol.market.common.widget.LoadingDrawable;
import com.mol.market.fanli.ui.TaskInformationActivity.RebateTask;

/**
 * 返利入口页面，显示返利产品列表。
 *
 * @author Chaos
 * @date 2012-7-31
 * @since Version 0.9.5
 */
public class MakeMoneyActivity extends LazyloadListActivity implements
    ApiRequestListener, OnItemClickListener, Observer {


  private AppListAdapter                     mAdapter;
  private ProgressBar                        mProgress;
  private TextView                           mNoData;
  private TextView                           mBalance;

  private HashMap<String, String> mTaskNames = new HashMap<String, String>();
  private int mTotalSize;

  @Override
  protected void onResume() {
    super.onResume();
    if (mAdapter != null) {
      mAdapter.notifyDataSetChanged();
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    mSession.cashbackManager.deleteObserver(this);
    mAdapter.recycle();
    mAdapter = null;
  }

  @Override
  public boolean doInitView(Bundle savedInstanceState) {

    setContentView(R.layout.fanli_activity_makemoney);

    mSession.cashbackManager = CashbackManager.get(getApplicationContext());
    mSession.cashbackManager.requestBalance();
    mSession.cashbackManager.addObserver(this);

    initTopBar();

    initView();

    lazyload();

    if (mSession.isFirstRebate()) {
      // 第一次进入返利时弹出引导对话框
      Intent i = new Intent(getApplicationContext(),
          ExchangeGuideActivity.class);
      startActivity(i);
      mSession.setRebated();
    }

    return true;
  }

  @Override
  public void doLazyload() {
    MarketAPI.getExchangeTask(this, this, getStartIndex(),
        getItemsPerPage());
  }


  @Override
  public AppListAdapter doInitListAdapter() {
    // 绑定返利任务列表数据
    mAdapter = new AppListAdapter(getApplicationContext(),
        null,
        R.layout.rebate_list_item,
        new String[] {
            Constants.KEY_PRODUCT_ICON_URL,
            Constants.KEY_PRODUCT_NAME,
            Constants.KEY_PRODUCT_SUB_CATEGORY,
            Constants.KEY_PRODUCT_IS_STAR,
            Constants.KEY_PRODUCT_SIZE,
            Constants.KEY_PRODUCT_DOWNLOAD },
        new int[] {
            R.id.iv_logo,
            R.id.tv_name,
            R.id.tv_description,
            R.id.iv_star,
            R.id.tv_size,
            R.id.tv_download });

    mAdapter.setActivity(this);
    mAdapter.setProductList();
    mList.setOnItemClickListener(this);
    mAdapter.setViewBinder(new ViewBinder() {
      @Override
      public boolean setViewValue(View view, Object data, int position,
                                  Object textRepresentation) {
        if (view.getId() == R.id.tv_download) {
          // 定制下载按钮
          @SuppressWarnings("unchecked")
          HashMap<String, Object> map = (HashMap<String, Object>) data;
          TextView v = (TextView) view;
          String pkgName = (String) map.get(Constants.KEY_PRODUCT_PACKAGE_NAME);
          CashbackTask task = mSession.cashbackManager.getRebateTasks().get(pkgName);
          if (task != null) {
            map.put(Constants.KEY_REBATE_FLAG, task.status);
          }
          setViewText(position, v,
              (Integer) map.get(Constants.KEY_REBATE_FLAG));
          return true;
        }
        return false;
      }
    });
    return mAdapter;
  }

  @Override
  protected int getItemCount() {
    return mTotalSize;
  }

  /**
   * 初始化TopBar
   */
  private void initTopBar() {
    TopBar.createTopBar(mSession, this,
        new View[] {
          findViewById(R.id.top_bar_title),
          findViewById(R.id.top_bar_btn_exchange),
          findViewById(R.id.top_bar_tv_money) },
        new int[] {
          View.VISIBLE,
          View.VISIBLE,
          View.VISIBLE },
        getString(R.string.profit),
        getString(R.string.exchange));

    // 给兑换按钮添加响应事件
    findViewById(R.id.top_bar_btn_exchange).setOnClickListener(this);
  }

  /**
   * 初始化界面控件
   */
  private void initView() {

    // 加载进度条以及加载失败的重试按钮
    mList = (ListView) findViewById(android.R.id.list);
    FrameLayout mLoading = (FrameLayout) findViewById(R.id.loading);
    mProgress = (ProgressBar) findViewById(R.id.progressbar);
    mProgress.setIndeterminateDrawable(new LoadingDrawable(
        getApplicationContext()));
    mProgress.setVisibility(View.VISIBLE);
    mNoData = (TextView) findViewById(R.id.no_data);
    mNoData.setOnClickListener(this);
    mList.setEmptyView(mLoading);

    mBalance = (TextView) findViewById(R.id.top_bar_tv_money);
    mBalance.setText(getString(R.string.pay_unit,
        Utils.convertCentToYuan(
            mSession.cashbackManager.getBalance())));
  }

  @SuppressWarnings("unchecked")
  @Override
  public void onSuccess(int method, Object obj) {

    switch (method) {

      case MarketAPI.ACTION_GET_EXCHANGE_HOME_TASK:

        HashMap<String, Object> result = (HashMap<String, Object>) obj;

        if (mTotalSize <= 0) {
          // 获取总大小
          mTotalSize = (Integer) result.get(Constants.KEY_TOTAL_SIZE);
        }

        mAdapter.addDataList((ArrayList<HashMap<String, Object>>) result
                .get(Constants.KEY_TASK_LIST));
        setLoadResult(true);
        break;

      case MarketAPI.ACTION_GET_DOWNLOAD_URL:
        DownloadItem info = (DownloadItem) obj;
        mSession.cashbackManager.startTask(info.url, info.packageName,
            mTaskNames.get(info.pId));
        mTaskNames.remove(info.pId);
        break;

      default:
        break;
    }
  }

  @Override
  public void onError(int method, int statusCode) {

    switch (method) {

      case MarketAPI.ACTION_GET_EXCHANGE_HOME_TASK:

        // 获取数据异常
        mNoData.setVisibility(View.VISIBLE);
        mProgress.setVisibility(View.GONE);
        setLoadResult(false);
        break;

    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position,
                          long id) {
    // 点击去返利产品详细页
    Utils.trackEvent(getApplicationContext(), Constants.GROUP_REBATE,
        Constants.REBATE_CLICK_DETAIL);

    HashMap<String, Object> item = (HashMap<String, Object>) mAdapter.getItem(position);
    String pid = (String) item.get(Constants.KEY_ID);
    Intent detailIntent = new Intent(getApplicationContext(),
        FanliPreloadActivity.class);
    detailIntent.putExtra(Constants.EXTRA_PRODUCT_ID, pid);
    startActivity(detailIntent);
  }

  @Override
  public void onClick(View v) {
    if (v.getId() == R.id.top_bar_btn_exchange) {
      Utils.jumpToPage(this, ExchangeActivityOther.class, false);
    } else {
      // 重试
      mProgress.setVisibility(View.VISIBLE);
      mNoData.setVisibility(View.GONE);
      lazyload();
    }
  }

  /*
  * Set text value for TextView
  */
  private void setViewText(int position, TextView v, final int flag) {
    int level;
    switch (flag) {
      case RebateTask.STATUS_NORMAL:
        // 准备下载
        level = 0;
        v.setText(getString(R.string.label_profit));
        break;
      case RebateTask.STATUS_FAIL:
        // 返利失败任务
      case RebateTask.STATUS_REBATED:
        // 已返利
        level = 11;
        v.setText(getString(R.string.rebate_complete));
        break;
      case RebateTask.STATUS_DOWNLOADING:
        // 开始下载
        level = 10;
        v.setText(getString(R.string.download_status_downloading));
        break;
      case RebateTask.STATUS_DOWNLOADED:
        // 下载完成
        level = 9;
        v.setText(getString(R.string.download_status_downloaded));
        break;
      case RebateTask.STATUS_INVALID:
        // 无效任务
        level = 11;
        v.setText(getString(R.string.rebate_invalid));
        break;
      default:
        level = 11;
        v.setText(getString(R.string.rebate_complete));
        break;
    }
    setStateByLevel(v, level, position);
  }

  /**
   * 根据当前状态设置图片。
   *
   * @param v
   * @param level
   * @param pos
   */
  private void setStateByLevel(final TextView v, final int level,
      final int pos) {
    Drawable[] drawableArray = v.getCompoundDrawables();
    if (drawableArray[1] != null) {
      drawableArray[1].setCallback(null);
    }
    v.setCompoundDrawablesWithIntrinsicBounds(0,
        R.drawable.btn_downloading, 0, 0);
    Drawable indicatorDrawable = v.getCompoundDrawables()[1];
    indicatorDrawable.setLevel(level);

    // 为下载按钮绑定事件
    v.setOnClickListener(new OnClickListener() {

      @SuppressWarnings("unchecked")
      @Override
      public void onClick(View view) {
        doAction((HashMap<String, Object>) mAdapter.getItem(pos));
      }
    });
  }

  /**
   * 下载
   *
   * @param item
   */
  private void doAction(final HashMap<String, Object> item) {

    String id = (String) item.get(Constants.KEY_PRODUCT_ID);
    String name = (String) item.get(Constants.KEY_PRODUCT_NAME);
    String pkgName = (String) item.get(Constants.KEY_PRODUCT_PACKAGE_NAME);

    Integer flag = (Integer) item.get(Constants.KEY_REBATE_FLAG);
    switch (flag) {
      case RebateTask.STATUS_NORMAL:
        // 准备下载
        mTaskNames.put(id, name);
        item.put(Constants.KEY_REBATE_FLAG, RebateTask.STATUS_DOWNLOADING);
        Utils.trackEvent(getApplicationContext(), Constants.GROUP_REBATE,
            Constants.REBATE_CLICK_DOWNLOAD_1);
        MarketAPI.getDownloadUrl(getApplicationContext(), this,
            id, Constants.SOURCE_TYPE_REBATE);
        break;
      case RebateTask.STATUS_REBATED:
        // 已返利
        break;
      case RebateTask.STATUS_DOWNLOADING:
        // 开始下载
        break;
      case RebateTask.STATUS_DOWNLOADED:
        // 下载完成
        mSession.cashbackManager.install(pkgName);
        Utils.trackEvent(getApplicationContext(), Constants.GROUP_REBATE,
            Constants.REBATE_CLICK_INSTALL_1);
        break;
      default:
        break;
    }
  }

  @Override
  public void update(Observable observable, Object data) {
    if (data instanceof HashMap) {
      if (mAdapter != null) {
        mAdapter.notifyDataSetChanged();
      }
    } else {
      if (mBalance != null) {
        mBalance.setText(getString(R.string.pay_unit,
            Utils.convertCentToYuan(
                mSession.cashbackManager.getBalance())));

      }
    }
  }

}
